package com.summo.demo.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    public ModelAndView handleError(HttpServletRequest request, HttpServletResponse response) {
        //获取当前响应返回的状态码
        int statusCode = response.getStatus();
        //如果响应头中存在statusCode，则默认使用这个statusCode
        if (StringUtils.isNotBlank(response.getHeader("statusCode"))) {
            statusCode = Integer.valueOf(response.getHeader("statusCode"));
        }
        if (statusCode == HttpServletResponse.SC_FOUND) {
            // 获取Location响应头的值，进行重定向
            String redirectLocation = response.getHeader("Location");
            return new ModelAndView("redirect:" + redirectLocation);
        } else if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
            // 重定向到登录页或指定页面
            if (StringUtils.isNotBlank(response.getHeader("redirectURL"))) {
                return new ModelAndView(
                    "redirect:/login?redirectURL=" + response.getHeader("redirectURL"));
            }
            return new ModelAndView("redirect:/login");
        } else if (statusCode == HttpServletResponse.SC_FORBIDDEN) {
            // 返回403页面
            return new ModelAndView("403");
        } else if (statusCode == HttpServletResponse.SC_NOT_FOUND) {
            // 返回404页面
            return new ModelAndView("404");
        } else if (statusCode == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) {
            // 返回500页面，并传递errorMsg和errorCode到模板
            ModelAndView modelAndView = new ModelAndView("500");
            modelAndView.addObject("errorMsg", response.getHeader("errorMsg"));
            modelAndView.addObject("errorCode", response.getHeader("errorCode"));
            return modelAndView;
        } else {
            // 返回其他错误页面
            return new ModelAndView("error");
        }
    }

}